package io.github.lee.core.repository.di.http

import android.content.Context
import io.github.lee.core.repository.di.http.interceptor.ResponseInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


private const val TIMEOUT = 10L
private val timeUnit = TimeUnit.SECONDS

object HttpModule {
    private var baseUrl = ""
    private val interceptorList = mutableListOf<Interceptor>()


    fun init(baseUrl: String, interceptorList: List<Interceptor>? = emptyList()) {
        HttpModule.baseUrl = baseUrl
        if (null != interceptorList) {
            HttpModule.interceptorList.clear()
            HttpModule.interceptorList.add(ResponseInterceptor())
            HttpModule.interceptorList.addAll(interceptorList)
        }
    }

    fun provideOkHttp(): OkHttpClient {
        val builder = OkHttpClient.Builder()
           .connectTimeout(TIMEOUT, timeUnit)
            .callTimeout(TIMEOUT, timeUnit)
            .readTimeout(TIMEOUT, timeUnit)
            .writeTimeout(TIMEOUT, timeUnit)


        if (interceptorList.isNotEmpty()) {
            interceptorList.forEach {
                builder.addInterceptor(it)
            }
        }
        return builder.build()
    }


    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(okHttpClient)
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }




}